﻿; ---------------------------------------------------------
; *********************************************************
; SELECT THE JA2 LANGUAGE VERSION OF THE SETUP
; *********************************************************
; English version comiple ............ "(EN)"
; German version compile ............. "(DE)"
; Russian version compile ............."(RU)"
; Polish version compile .............."(PL)"
#define APP_LANG_VERS           "(EN)"

; *********************************************************
; ENABLE THE MATCHING LANGUAGE APP_ID
; *********************************************************
; English version
#define APP_ID                   "1B3D4AC6-BE9B-4d4a-87A7-51B0197C8DEB"
; German version
; #define APP_ID                 "18230CE9-5715-46fc-BB49-E5E60D53342D"
; Russian version
; #define APP_ID                 "73964366-A9C4-4431-B8B2-435A3085812A"
; Polish version
; #define APP_ID                 "688A0385-AB13-46f4-A588-574981449B4E"
; Chinese version
; #define APP_ID                 "9D05F7F2-222C-4693-AC13-FFEA50C2F49D"

; *********************************************************
; ROOT FOLDER NAME, WHERE THE UPDATE FILES ARE LOCATED
; *********************************************************
; "Update" .............. for compiling the update
; "UpdateTest" .......... for testing purpose
#define APP_FILES_DIR           "Update"

; *********************************************************
; LANGUAGE SPECIFIC FOLDER NAME, WHERE THE UPDATE FILES ARE LOCATED
; *********************************************************
; "GameDir_EN" .......... English version
; "GameDir_DE" .......... German version
; "GameDir_RU" .......... Russian version
; "GameDir_PL" .......... Polish version
#define APP_LANG_FILES_DIR     "GameDir_EN"

; *********************************************************
; CHANGE THESE VERSION VALUES FOR A NEW SETUP BUILD
; *********************************************************
; New Release: Update MAJOR and BUILD
; New Update:  Upate BUILD
; Hint: No need to change MINOR OR RELEASE
#define MAJOR 1
#define MINOR 0
#define RELEASE 0
#define BUILD 5200

; *********************************************************
; THE PREVIOUS VERSION NUMBER OF THE LAST UPDATE -> LOOK IN THE REGISTRY KEY: UNINSTKEY -> DisplayVersion
; *********************************************************
#define APP_PREV_VER "1.0.0.4452"
; ---------------------------------------------------------


#define APP_NAME "Jagged Alliance 2 v1.13 " + APP_LANG_VERS
#define APP_PUBLISHER "Members of the Bear's Pit Forum"
#define APP_PUBLISHER_URL "http://ja2v113.pbwiki.com/"
#define APP_SUPPORT_URL "http://www.ja-galaxy-forum.com"
#define APP_UPDATES_URL "http://ja2v113.pbwiki.com/"
#define APP_EXE_NAME "ja2.exe"
#define APP_DEFAULT_INSTALL_FOLDER "Jagged Alliance 2"
#define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\" + APP_ID + "_is1"
#define APP_VER Str(MAJOR) + "." + Str(MINOR) + "." + Str(RELEASE) + "." + Str(BUILD)

[Setup]
AppName={#APP_NAME}
AppVerName={#APP_NAME} [{#APP_VER}]
AppVersion={#APP_VER}
AppId={#APP_ID}
AppPublisher={#APP_PUBLISHER}
AppPublisherURL={#APP_PUBLISHER_URL}
AppSupportURL={#APP_SUPPORT_URL}
AppUpdatesURL={#APP_UPDATES_URL}
WizardSmallImageFile=C:\stuff\1.13\Development\Source Code\Installer\Support\ja2logo.bmp
VersionInfoDescription={#APP_VER}
VersionInfoVersion={#APP_VER}
VersionInfoTextVersion={#APP_VER}
VersionInfoCompany={#APP_PUBLISHER}
; Do not append the "Install Folder" in the Browse Dialog
AppendDefaultDirName=false
DirExistsWarning=no
DefaultDirName={reg:HKLM\Software\Jagged Alliance 2 v1.13 {#APP_LANG_VERS}, Path|{pf}\{#APP_DEFAULT_INSTALL_FOLDER}}
DefaultGroupName={#APP_NAME}
OutputDir=C:\stuff\1.13\Development\Source Code\Installer\Output
OutputBaseFilename=JA2 v1.13 Update {#APP_LANG_VERS} [{#APP_VER}]
SetupIconFile=C:\stuff\1.13\Development\Source Code\Installer\Support\ja2.ico
Compression=lzma/ultra
SolidCompression=yes

[Languages]
Name: en; MessagesFile: compiler:Default.isl; InfoBeforeFile: C:\stuff\1.13\Development\Source Code\Installer\Support\Revision_History_Update_EN.rtf
Name: de; MessagesFile: compiler:Languages\German.isl; InfoBeforeFile: C:\stuff\1.13\Development\Source Code\Installer\Support\Revision_History_Update_DE.rtf
Name: ru; MessagesFile: compiler:Languages\Russian.isl; InfoBeforeFile: C:\stuff\1.13\Development\Source Code\Installer\Support\Revision_History_Update_EN.rtf
Name: pl; MessagesFile: compiler:Languages\Polish.isl; InfoBeforeFile: C:\stuff\1.13\Development\Source Code\Installer\Support\Revision_History_Update_EN.rtf
Name: ch; MessagesFile: compiler:Languages\Chinese.isl; InfoBeforeFile: C:\stuff\1.13\Development\Source Code\Installer\Support\Revision_History_Update_CH.rtf

[Types]
; Do not show the "Complete installation, minimal installation, custom installation" drop down
Name: full_install; Description: {cm:full_install}; Flags: iscustom

[CustomMessages]
; -----------------------------
; Latest version already installed
; -----------------------------
en.NewerAppFound=The latest version [%s] of '{#APP_NAME}' is already installed.
en.NotVerifiedVersionFound=Setup has detected an installed version of '{#APP_NAME}', but \
 it cannot verify its version number.%n \
 It's possible that the installed product is already a newer version.%n \
 Would you like to proceed with the installation at your own risk?
en.NotValidUpdate=You have to install version [%s] of '{#APP_NAME}' first.

de.NewerAppFound=Es ist bereits die aktuellste Version [%s] von '{#APP_NAME}' installiert.
de.NotVerifiedVersionFound={'#APP_NAME}' ist vermutlich schon installiert worden, aber Setup \
  kann die Version nicht zweifelsfrei ermitteln.%n \
  Es besteht die Möglichkeit, dass die bereits installierte Version aktueller ist.%n \
  Wollen Sie die Installation trotzdem und auf eigenes Risiko fortsetzen?
de.NotValidUpdate=Sie müssen vorher die Version [%s] von '{#APP_NAME}' installieren.

ru.NewerAppFound=Ïîñëåäíÿÿ âåðñèÿ [%s] ïðèëîæåíèÿ '{#APP_NAME}' óæå óñòàíîâëåíà íà âàøåì êîìïüþòåðå.
ru.NotVerifiedVersionFound=Ïðîãðàììà óñòàíîâêè îáíàðóæèëà óæå óñòàíîâëåííîå ïðèëîæåíèå '{#APP_NAME}', íî \
 íå ñìîãëà îïðåäåëèòü åãî âåðñèþ.%n \
 Åñòü âåðîÿòíîñòü òîãî, ÷òî ó âàñ óñòàíîâëåíà áîëåå íîâàÿ âåðñèÿ.%n \
 Æåëàåòå ëè âû âñ¸ ðàâíî ïðîäîëæèòü óñòàíîâêó íà ñâîé ñòðàõ è ðèñê?
ru.NotValidUpdate=Ñïåðâà âû äîëæíû óñòàíîâèòü âåðñèþ [%s] ïðèëîæåíèÿ '{#APP_NAME}'.

pl.NewerAppFound=Najnowsza wersja [%s] of '{#APP_NAME}' jest ju? zainstalowana.
pl.NotVerifiedVersionFound=Instalator wykryі zainstalowan№ wersjк '{#APP_NAME}', ale \
 nie moїe okreњliж jej numeru.%n \
 Moїliwe, їe zainstalowany produkt to nowsza wersja.%n \
 Czy chcesz kontynuowaж na wіasne ryzyko?
pl.NotValidUpdate=You have to install version [%s] of '{#APP_NAME}' first.

ch.NewerAppFound='{#APP_NAME}' 的最新版本 [%s] 已经安装。
ch.NotVerifiedVersionFound=安装程序检测到 '{#APP_NAME}' 的已安装版本，但 \
  不能验证其版本号。%n \
  已安装版本可能已经是较新版本。%n \
  你想继续安装？（自行承担风险）
ch.NotValidUpdate=你必须先安装 [%s] 版本的 '{#APP_NAME}' 。

; ----------------------------
; Uninstall icon text
; ----------------------------
en.RemoveApp =Remove {#APP_NAME}
de.RemoveApp ={#APP_NAME} entfernen
ru.RemoveApp =Óäàëèòü {#APP_NAME}
pl.RemoveApp =Remove {#APP_NAME}
ch.RemoveApp =Remove {#APP_NAME}

en.global_settings =Global settings
de.global_settings =Globale Einstellungen
ru.global_settings =Îáùèå íàñòðîéêè
pl.global_settings =Global settings
ch.global_settings =Global settings

en.ja2v113_settings =Gameplay settings
de.ja2v113_settings =Spieleinstellungen
ru.ja2v113_settings =Èãðîâûå íàñòðîéêè
pl.ja2v113_settings =Gameplay settings
ch.ja2v113_settings =Global settings

en.start_ja2v113 =Play {#APP_NAME}
de.start_ja2v113 ={#APP_NAME} starten
ru.start_ja2v113 =Çàïóñòèòü {#APP_NAME}
pl.start_ja2v113 =Play {#APP_NAME}
ch.start_ja2v113 =Play {#APP_NAME}

; ----------------------------
; Type
; ----------------------------
en.full_install =Complete installation
de.full_install =Komplette Installation
ru.full_install =Ïîëíàÿ óñòàíîâêà
pl.full_install =Zakoсcz instalacjк
ch.full_install =完成安装

; Wrong directory selected
en.wrong_directory =Please select your existing 'Jagged Alliance 2 v1.13' installation folder.
de.wrong_directory =Bitte wählen Sie den vorhandenen 'Jagged Alliance 2 v1.13' Installationsordner.
ru.wrong_directory =Óêàæèòå ïðàâèëüíûé ïóòü ê êîðíåâîé ïàïêå èãðû 'Jagged Alliance 2 v1.13'.
pl.wrong_directory =Wybierz folder, gdzie zainstalowane jest Jagged Alliance 2.
ch.wrong_directory =请选择已安装的“Jagged Alliance 2”所在目录

[Tasks]
; Create desktop icon after installation (Check box)
Name: desktopicon; Description: {cm:CreateDesktopIcon}; GroupDescription: {cm:AdditionalIcons}; Flags: unchecked

[Files]
; ------------------------
; Backup files from vanilla Jagged Alliance 2 that are overwritten with files from Jagged Alliance 2 v1.13
; ------------------------
Source: {app}\ja2.ini; DestDir: {app}\Data\TempBackup; Flags: external uninsneveruninstall; Check : FileIni
Source: {app}\ja2.exe; DestDir: {app}\Data\TempBackup; Flags: external uninsneveruninstall; Check : FileExe
Source: {app}\ja2.set; DestDir: {app}\Data\TempBackup; Flags: external uninsneveruninstall; Check : FileSet

; -----------------------
; Jagged Alliance 2 v1.13 files
; -----------------------
; Main game data
Source: C:\stuff\1.13\Development\Source Code\Installer\Setup Files\{#APP_FILES_DIR}\GameDir_Global\*; DestDir: {app}; Flags: ignoreversion recursesubdirs createallsubdirs replacesameversion;
Source: C:\stuff\1.13\Development\Source Code\Installer\Setup Files\{#APP_FILES_DIR}\{#APP_LANG_FILES_DIR}\*; DestDir: {app}; Flags: ignoreversion recursesubdirs createallsubdirs replacesameversion;

[Icons]
; Create desktop icon?
Name: {userdesktop}\{#APP_NAME}; Filename: {app}\{#APP_EXE_NAME}; Tasks: desktopicon
; Global settings (ja2.ini)
Name: {group}\{cm:global_settings}; Filename: {app}\ja2.ini
; JA2 v1.13 settings (ja2_options.ini)
Name: {group}\{cm:ja2v113_settings}; Filename: {app}\Data-1.13\Ja2_Options.ini
; Folder in the start menu
Name: {group}\{cm:start_ja2v113}; Filename: {app}\{#APP_EXE_NAME}
; Remove application
Name: {group}\{cm:RemoveApp}; Filename: {uninstallexe}

[Run]
; Files that can start after the installation
Filename: {app}\{#APP_EXE_NAME}; Description: {cm:LaunchProgram,{#APP_NAME}}; Flags: nowait postinstall skipifsilent

[Registry]
Root: HKLM; Subkey: Software\Jagged Alliance 2 v1.13 {#APP_LANG_VERS}; ValueType: string; ValueName: Path; ValueData: {app}; Flags: uninsdeletekey

[Code]
// ----------------------------------------------------------------------------
function FileIni : boolean;
// ----------------------------------------------------------------------------
begin
  result:= FileExists(ExpandConstant('{app}\ja2.ini'));
end;

// ----------------------------------------------------------------------------
function FileExe : boolean;
// ----------------------------------------------------------------------------
begin
  result:= FileExists(ExpandConstant('{app}\ja2.exe'));
end;

// ----------------------------------------------------------------------------
function FileSet : boolean;
// ----------------------------------------------------------------------------
begin
  result:= FileExists(ExpandConstant('{app}\ja2.set'));
end;

// ----------------------------------------------------------------------------
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
// ----------------------------------------------------------------------------
var
  FindRec: TFindRec;
begin
  // Uninstall of JA2 v1.13 is complete
  if CurUninstallStep = usDone then
  begin
    // TempBackup folder exists?
    if FindFirst(ExpandConstant('{app}\Data\TempBackup\*'), FindRec) then
    begin
      try
        repeat
          // Copy the files from TempBackup back to the game directory
          FileCopy(ExpandConstant('{app}\Data\TempBackup\') + FindRec.Name, ExpandConstant('{app}\') + FindRec.Name, false);
          // Delete the filess from TempBackup
          DeleteFile(ExpandConstant('{app}\Data\TempBackup\') + FindRec.Name);
        until not FindNext(FindRec);
      finally
        FindClose(FindRec);
      end;
      // Delete the TempBackup folder
      if DirExists(ExpandConstant('{app}\Data\TempBackup\')) then
        RemoveDir(ExpandConstant('{app}\Data\TempBackup\'));
    end;
  end;
end;

// ----------------------------------------------------------------------------
function IsValidUpdate: boolean;
// ----------------------------------------------------------------------------
var
  SavedVersion : string;
  validUpdate : boolean;

begin
  validUpdate := false;

  // Registry key does not exists (ERROR) -> no matter, take the current update as a valid update
  if (not RegQueryStringValue(HKEY_LOCAL_MACHINE, '{#UNINSTKEY}','DisplayVersion', SavedVersion )) then
  begin
    validUpdate := true;
  end
  else
  begin
    if ('{#APP_PREV_VER}' = SavedVersion) then
    begin
      validUpdate := true;
    end
    else
    begin
      MsgBox(Format(ExpandConstant('{cm:NotValidUpdate}'), ['{#APP_PREV_VER}']), mbError, MB_OK);
    end;
  end;

  Result := validUpdate;
end;

// ----------------------------------------------------------------------------
function NextButtonClick(CurPageID: Integer): Boolean;
// ----------------------------------------------------------------------------
begin
  Result := True;
	case CurPageID of
		wpSelectDir:
		begin
			//MsgBox('NextButtonClick:' #13#13 'You selected: ''' + WizardDirValue + '''.', mbInformation, MB_OK);
      if DirExists(WizardDirValue + '\Data') and DirExists(WizardDirValue + '\Data-1.13') then
			begin
        // Selected install directory is the Jagged Alliance 2 installation folder -> Continue
			  Result := True;
      end
			else
			begin
        // Selected install directory is not the Jagged Alliance 2 installation folder
			  MsgBox(ExpandConstant('{cm:wrong_directory}'), mbError, MB_OK);
			  Result := False;
			end;
		end;
	end;
end;

// ----------------------------------------------------------------------------
function CreateDWord(const Hi, Lo: word): dword;
// ----------------------------------------------------------------------------
begin
  Result := (Hi shl 16) or Lo;
end;

// ----------------------------------------------------------------------------
function DecodeVersion(const dwMajor, dwMinor: dword): string;
// ----------------------------------------------------------------------------
var
  a, b, c, d : word;
begin
  a := word(dwMajor shr 16);
  b := word(dwMajor and not $ffff0000);
  c := word(dwMinor shr 16);
  d := word(dwMinor and not $ffff0000);
  
  Result := IntToStr(a) + '.' + IntToStr(b) + '.' + IntToStr(c) + '.' + IntToStr(d);
end;

// ----------------------------------------------------------------------------
function IsSetupNewer: boolean;
// ----------------------------------------------------------------------------
var
  SetupMajor, SetupMinor, SavedMajor, SavedMinor : dword;
  tmp : string;
begin

  if (not RegQueryDWordValue(HKLM, '{#UNINSTKEY}', 'MajorVer', SavedMajor)) or
    (not RegQueryDWordValue(HKLM,'{#UNINSTKEY}','MinorVer',SavedMinor)) then
  begin
    if(RegQueryStringValue(HKLM,'{#UNINSTKEY}','UninstallString',tmp)) and
      (tmp <> '') and (fileexists(tmp)) then
    begin
      Result := (MsgBox(ExpandConstant('{cm:NotVerifiedVersionFound}'),
        mbConfirmation, MB_YESNO or MB_DEFBUTTON2) = IDYES);
      exit;
    end;
  end;
  
  SetupMajor := CreateDWord({#MAJOR}, {#MINOR});
  SetupMinor := CreateDWord({#RELEASE}, {#BUILD});
  
  Result := (SetupMajor > SavedMajor) or
    ((SetupMajor = SavedMajor) and (SetupMinor >= SavedMinor));
    
  if (not Result) then
  begin
    MsgBox(Format(ExpandConstant('{cm:NewerAppFound}'), [DecodeVersion(SavedMajor, SavedMinor)]), mbError, MB_OK);
  end;
end;

// ----------------------------------------------------------------------------
function SaveVersionInfo: boolean;
// ----------------------------------------------------------------------------
begin
  Result := (RegWriteDWordValue(HKLM,'{#UNINSTKEY}','MajorVer', CreateDWord({#MAJOR},{#MINOR})))
    and (RegWriteDWordValue(HKLM,'{#UNINSTKEY}','MinorVer', CreateDWord({#RELEASE},{#BUILD})));
end;

// ----------------------------------------------------------------------------
function InitializeSetup: boolean;
// ----------------------------------------------------------------------------
begin

  // Is the current setup a never version
  Result := IsSetupNewer;
  
  // INFO: IF WE DO NOT LIKE A VERSION CONTROL, DISABLE THE FOLLOWING IF-COMMAND!
  //if (Result) then
    // Is the current setup a valid (next) update
    //Result := IsValidUpdate;
end;

// ----------------------------------------------------------------------------
procedure CurStepChanged(CurrentStep: TSetupStep);
// ----------------------------------------------------------------------------
begin
  if (CurrentStep = ssPostInstall) then
  begin
    SaveVersionInfo;
  end;
end;

